package com.jiyici;

import java.util.ArrayList;

import jiyici.Constant.ItemParamType;
import jiyici.ParamType;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.jiyici.controller.DataManager;
import com.jiyici.model.Item;
import com.jiyici.model.ItemParam;
import com.jiyici.model.ModelUtil;
import com.jiyici.model.Record;
import com.jiyici.model.RecordParam;
import com.jiyici.utils.DateUtil;
import com.jiyici.utils.StringUtils;
import com.jiyici.view.DialogUtil;
import com.jiyici.view.DialogWrapper.DialogAction;

public class RecordActivity extends SherlockActivity {

    private ActionMode mActionMode;
    private Item mItem;
    private Record mRecord;

    @Override
    protected void onCreate(Bundle arg0) {
        GlobalTheme.applyTheme(this, true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mItem = (Item) getIntent().getSerializableExtra("item");
        mRecord = (Record) getIntent().getSerializableExtra("record");
        getSupportActionBar().setTitle(
                ViewUtil.getTitle(mItem.itemName + ": " + DateUtil.stringDateTime(mRecord.recordTime)));

        super.onCreate(arg0);
        setContentView(R.layout.activity_record);

        gotoDisplayMode();

    }

    private void gotoDisplayMode() {
        edits = null;
        Item item = mItem;
        final ViewGroup property_input_layout = (ViewGroup) findViewById(R.id.edit_table);
        property_input_layout.removeAllViews();
        LayoutInflater layoutinflater = LayoutInflater.from(this);
        final int propertySize = item.params.size();
        for (int i = 0; i < propertySize; i++) {
            ItemParam param = item.params.get(i);
            View propertyInput = layoutinflater.inflate(R.layout.display_row, property_input_layout, false);
            TextView propertyName = (TextView) propertyInput.findViewById(R.id.label);
            TextView propertyEdit = (TextView) propertyInput.findViewById(R.id.edit);

            propertyName.setText(param.itemParamName);
            String value = ModelUtil.getRecordItemValue(mRecord, param);
            propertyEdit.setText(value);
            property_input_layout.addView(propertyInput);
            property_input_layout.addView(layoutinflater.inflate(R.layout.divider, property_input_layout, false));
        }
    }

    private EditText[] edits;

    private void gotoEditMode() {
        Item item = mItem;
        final ViewGroup property_input_layout = (ViewGroup) findViewById(R.id.edit_table);
        property_input_layout.removeAllViews();
        LayoutInflater layoutinflater = LayoutInflater.from(this);
        final int propertySize = item.params.size();
        edits = new EditText[propertySize];
        for (int i = 0; i < propertySize; i++) {
            ItemParam param = item.params.get(i);
            View propertyInput = layoutinflater.inflate(R.layout.edit_row, property_input_layout, false);
            TextView propertyName = (TextView) propertyInput.findViewById(R.id.label);
            EditText propertyEdit = (EditText) propertyInput.findViewById(R.id.edit);
            edits[i] = propertyEdit;
            String hint = getString(ParamType.getParamType(param.paramType).typeHint);
            if (param.isMust) {
                hint = "*" + hint;
            }
            propertyEdit.setHint(hint);
            int inputtype = EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE;
            if (param.paramType == ItemParamType.NUMBER) {
                inputtype = EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_FLAG_DECIMAL
                        | EditorInfo.TYPE_NUMBER_FLAG_SIGNED;
            } else {
                propertyEdit.setSingleLine(false);
            }
            propertyEdit.setInputType(inputtype);
            propertyEdit.setText(ModelUtil.getRecordItemValue(mRecord, param));
            propertyName.setText(param.itemParamName);
            propertyInput.setTag(param);
            property_input_layout.addView(propertyInput);
            property_input_layout.addView(layoutinflater.inflate(R.layout.divider, property_input_layout, false));
        }
    }

    private boolean saveEdit() {
        /* check data input */
        int propertySize = mItem.params.size();
        ArrayList<RecordParam> params = new ArrayList<RecordParam>(propertySize + 1);
        for (int i = 0; i < propertySize; i++) {
            ItemParam param = mItem.params.get(i);
            EditText propertyEdit = edits[i];
            String value = propertyEdit.getText().toString().trim();
            if (param.isMust && StringUtils.isBlank(value)) {
                propertyEdit.requestFocus();
                return false;
            }
            RecordParam recordParam = ModelUtil.getRecordItem(mRecord, param);
            if (recordParam == null) {
                recordParam = new RecordParam();
                recordParam.itemParamId = param.getId();
                recordParam.value = value;
                params.add(recordParam);
                mRecord.paramList.add(recordParam);
            } else {
                if (!StringUtils.equal(recordParam.value, value)) {
                    recordParam.value = value;
                    params.add(recordParam);
                }
            }
        }
        /* data not changed */
        if (params.size() == 0)
            return true;
        DataManager.saveRecord(mRecord, params);
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(R.string.actionbar_item_edit).setIcon(R.drawable.ic_action_edit)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        SubMenu subMenu = menu.addSubMenu(R.string.menus);
        subMenu.add(R.string.actionbar_item_delete_record).setShowAsAction(
                MenuItem.SHOW_AS_ACTION_NEVER | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        subMenu.getItem().setIcon(R.drawable.abc_ic_menu_moreoverflow_normal_holo_dark)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            finish();
            return true;
        }
        if (getText(R.string.actionbar_item_edit).equals(item.getTitle())) {
            mActionMode = startActionMode(new RecordEditActionMode());
            return true;
        }
        if (getText(R.string.actionbar_item_delete_record).equals(item.getTitle())) {
            DialogUtil.showConfirmDialog(this, getString(R.string.actionbar_item_delete_record),
                    getString(R.string.dialog_confirm_delete_record), new DialogAction() {

                        @Override
                        public int run() {
                            DataManager.deleteRecord(mRecord);
                            finish();
                            return DISMISS;
                        }
                    });
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    class RecordEditActionMode implements ActionMode.Callback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            menu.add(R.string.actionbar_item_cancel).setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
            menu.add(R.string.actionbar_item_done).setShowAsAction(
                    MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
            gotoEditMode();
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            ViewUtil.hideKeyboard(RecordActivity.this);
            if (getText(R.string.actionbar_item_cancel).equals(item.getTitle())) {
                if (mActionMode != null) {
                    mActionMode.finish();
                    mActionMode = null;
                }
                return true;
            }
            if (getText(R.string.actionbar_item_done).equals(item.getTitle())) {
                if (saveEdit()) {
                    if (mActionMode != null) {
                        mActionMode.finish();
                        mActionMode = null;
                    }
                }
                return true;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            gotoDisplayMode();

        }

    }
}
